package org.example.user.listener;



import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.cassell_client.service.UserServiceClient;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;
@Slf4j
@RequiredArgsConstructor
@Component
public class UserListener {
    private final UserServiceClient userServiceClient;
    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(name="admin.user.success.queue" ,durable = "true"),
            exchange = @Exchange(name="user.direct"),
            key = "user.success"
    ))
    public void listen(Message message) {
        try {
            String jsonBody = new String(message.getBody(), StandardCharsets.UTF_8);
            log.info("接收的原始消息内容：{}", jsonBody);

            Map<String, String> params = new ObjectMapper().readValue(jsonBody, Map.class);
            userServiceClient.updateUser(params);
        } catch (Exception e) {
            log.error("消息处理失败", e);
            throw new AmqpRejectAndDontRequeueException("消息格式错误", e);
        }
    }
}